package com.example.jobback.service.seeker.impl;

import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.CollectMapper;
import com.example.jobback.mapper.DeliverMapper;
import com.example.jobback.po.*;
import com.example.jobback.resp.seeker.position.CollectResp;
import com.example.jobback.resp.seeker.position.GetPositionDetailResp;
import com.example.jobback.resp.seeker.position.GetRecruiterPositionResp;
import com.example.jobback.resp.seeker.position.SeekerCandidateResp;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.recruiter.RecruiterCrossService;
import com.example.jobback.service.seeker.SeekerPositionService;
import com.example.jobback.util.CACHEUtil;
import com.example.jobback.util.TLUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.jobback.util.RedisConstants.*;

/**
 * @ClassName: SeekerPositionServiceImpl
 * @Description:求职者-职位接口实现类
 * @Author: lhb
 * @Date: 2025/7/15
 */
@Service
public class SeekerPositionServiceImpl implements SeekerPositionService {

    private final CACHEUtil cacheUtil;

    private final RecruiterCrossService recruiterCrossService;

    private final UserCommonService userCommonService;

    private final DeliverMapper deliverMapper;

    private final AuthConfig authConfig;

    private final CollectMapper collectMapper;
    

    public SeekerPositionServiceImpl(CACHEUtil cacheUtil, RecruiterCrossService recruiterCrossService, UserCommonService userCommonService, DeliverMapper deliverMapper, AuthConfig authConfig, CollectMapper collectMapper) {
        this.cacheUtil = cacheUtil;
        this.recruiterCrossService = recruiterCrossService;
        this.userCommonService = userCommonService;
        this.deliverMapper = deliverMapper;
        this.authConfig = authConfig;
        this.collectMapper = collectMapper;
    }

    /**
     * @Description:  获取热门城市
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/15 16:32
     */
    @Override
    public Result<Object> getHotCityList() {
        Set<String> hotCityList = cacheUtil.getAllMembersFromSet(HOT_POSITION_CITIES_KEY);
        return Result.success(hotCityList);
    }

    /**
     * @Description: 根据userId获取该人发布的岗位
     * @param userId 
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/16 9:12
     */
    @Override
    public Result<List<GetRecruiterPositionResp>> getRecruiterPositions(Long userId) {
        List<GetRecruiterPositionResp> respList = new ArrayList<>();
        List<Position> positionList = recruiterCrossService.getPositionsByUserId(userId);
        if(positionList.isEmpty()) {
            return Result.success(respList);
        }
        User user = userCommonService.getUserByUserId(userId);
        Long companyId = positionList.get(0).getCompanyId();
        Company company = recruiterCrossService.getCompanyMessage(companyId);
        String companyAvatar = company.getAvatar();
        String companyName = company.getName();
        String userName = user.getName();
        String userAvatar = user.getAvatar();
        for (Position position : positionList) {
            GetRecruiterPositionResp resp = new GetRecruiterPositionResp();
            BeanUtils.copyProperties(position, resp);
            resp.setCompanyName(companyName);
            resp.setCompanyAvatar(companyAvatar);
            resp.setUserAvatar(userAvatar);
            resp.setUserName(userName);
            respList.add(resp);
        }
        return Result.success(respList);
    }

    /**
     * @Description: 根据职位id查看职位详细
     * @param positionId 
     * @return Result<GetPositionDetailResp>
     * @Author lhb
     * @CreateTime 2025/7/16 14:44
     */
    @Override
    public Result<GetPositionDetailResp> getPositionDetail(Long positionId) {
        GetPositionDetailResp resp = new GetPositionDetailResp();
        Position position = recruiterCrossService.getPositionById(positionId);
        if(position == null) {
            throw new NullPointerException("无此岗位信息");
        }
        Long userId = position.getUserId();
        Long companyId = position.getCompanyId();
        User user = userCommonService.getUserByUserId(userId);
        Recruiter recruiter = recruiterCrossService.getRecruiterByUserId(userId);
        Company company = recruiterCrossService.getCompanyMessage(companyId);
        BeanUtils.copyProperties(position, resp);
        resp.setUserName(user.getName());
        resp.setUserAvatar(user.getAvatar());
        resp.setRole(recruiter.getRole());
        resp.setCompanyName(company.getName());
        resp.setCompanyAvatar(company.getAvatar());
        return Result.success(resp);
    }

    /**
     * @Description: 收藏岗位
     * @param positionId
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/17 9:28
     */
    @Override
    public Result<Object> collectPositionById(Long positionId, Boolean status) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Long seekerUserId = seeker.getUserId();
        Collect collect =new Collect();
        collect.setSeekerUserId(seekerUserId);
        collect.setPositionId(positionId);
        collect.setStatus(status);
        if(!status) {
            if(collectMapper.update(collect) == 0) {
                throw new RuntimeException("操作失败");
            }
            return Result.success();
        }
        collectMapper.collectPosition(collect);
        return Result.success();
    }

    /**
     * @Description: 投递岗位
     * @param positionId 
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/17 9:35
     */
    @Override
    public Result<Object> deliverPositionById(Long positionId) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Position position = recruiterCrossService.getPositionById(positionId);
        if(position == null) {
            throw new NullPointerException("岗位不存在");
        }
        Deliver deliver = new Deliver();
        deliver.setPositionId(positionId);
        deliver.setSeekerUserId(seeker.getUserId());
        deliver.setRecruiterUserId(position.getUserId());
        deliver.setInterview(false);
        Deliver deliverByUnique = deliverMapper.getDeliverByUnique(deliver);
        if(deliverByUnique == null) {
            deliverMapper.insert(deliver);
        } else {
            if(deliverByUnique.getInterview()) {
                throw new IllegalArgumentException("VALIDATION_ERROR：投递失败，面试后不可再投递");
            }
            deliver.setId(deliverByUnique.getId());
            if( deliverMapper.update(deliver) ==0) {
                throw new RuntimeException("操作失败");
            }
        }
        String token = userCommonService.updateRedisUserToken(seeker.getUserId(), SEEKER_KEY,
                authConfig.getJwtSeekerSecret(), SEEKER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("生成token失败");
        return Result.success(token);
    }

    /**
     * @Description:  获取已投递
     * @return Result<List<SeekerGetDeliverResp>>
     * @Author lhb
     * @CreateTime 2025/7/17 11:16
     */
    @Override
    public Result<List<SeekerCandidateResp>> getDeliverList() {
        List<SeekerCandidateResp> respList = new ArrayList<>();
        Seeker seeker = TLUtil.get(TLUtil.S);
        List<Deliver> deliverList = deliverMapper.getDeliverBySeekerUserId(seeker.getUserId());
        if(deliverList.isEmpty()) {
            return Result.success(respList);
        }
        respList = getCandidateList(deliverList);
        return Result.success(respList);
    }

    /**
     * @Description:  获取已面试
     * @return Result<List<SeekerCandidateResp>>
     * @Author lhb
     * @CreateTime 2025/7/17 16:40
     */
    @Override
    public Result<List<SeekerCandidateResp>> getInterviewList() {
        List<SeekerCandidateResp> respList = new ArrayList<>();
        Seeker seeker = TLUtil.get(TLUtil.S);
        List<Deliver> deliverList = deliverMapper.getInterviewsBySeekerUserId(seeker.getUserId());
        if(deliverList.isEmpty()) {
            return Result.success(respList);
        }
        respList = getCandidateList(deliverList);
        return Result.success(respList);
    }

    /**
     * @Description: 获取已收藏
     * @return Result<List<CollectResp>>
     * @Author lhb
     * @CreateTime 2025/7/21 16:18
     */
    @Override
    public Result<List<CollectResp>> getCollectList() {
        List<CollectResp> respList = new ArrayList<>();
        Seeker seeker = TLUtil.get(TLUtil.S);
        List<Long> positionIds = collectMapper.getCollectJobIdsBySeekerUserId(seeker.getUserId());
        if(positionIds.isEmpty()) {
            return Result.success(respList);
        }
        //根据positionId查询其他相关信息
        List<Position> positionList = recruiterCrossService.getPositionByIds(positionIds);
        List<Long> userIds = positionList.stream()
                .map(Position::getUserId)
                .filter(Objects::nonNull)
                .toList();
        List<Long> companyIds = positionList.stream()
                .map(Position::getCompanyId)
                .filter(Objects::nonNull)
                .toList();
        List<User> userList = userCommonService.getUsersByUserIds(userIds);
        List<Company> companyList = recruiterCrossService.getCompanyMessagesByIds(companyIds);
        List<Recruiter> recruiterList = recruiterCrossService.getRecruiterByUserIds(userIds);
        //构建map
        Map<Long, User> userMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, user -> user));
        Map<Long, Recruiter> recruiterMap = recruiterList.stream()
                .collect(Collectors.toMap(Recruiter::getUserId, recruiter -> recruiter));
        Map<Long, Company> companyMap = companyList.stream()
                .collect(Collectors.toMap(Company::getCompanyId, company -> company));
        for (Position position : positionList) {
            CollectResp resp = new CollectResp();
            User user = userMap.get(position.getUserId());
            Recruiter recruiter = recruiterMap.get(position.getUserId());
            Company company = companyMap.get(position.getCompanyId());
            resp.setAvatar(user.getAvatar());
            resp.setName(user.getName());
            resp.setCompanyAvatar(company.getAvatar());
            resp.setCompanyIndustry(company.getCompanyIndustry());
            resp.setCompanyName(company.getName());
            resp.setRole(recruiter.getRole());
            resp.setRecruiterUserId(position.getUserId());
            BeanUtils.copyProperties(position, resp);
            respList.add(resp);
        }
        return Result.success(respList);
    }

    /**
     * @Description: 判断是否已收藏
     * @param positionId
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/21 17:14
     */
    @Override
    public Result<Object> judgeCollect(Long positionId) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Boolean status = collectMapper.judgeCollect(seeker.getUserId(), positionId);
        if(Objects.isNull(status)) status =false;
        return Result.success(status);
    }

    private List<SeekerCandidateResp> getCandidateList(List<Deliver> deliverList) {
        List<SeekerCandidateResp> respList = new ArrayList<>();
        List<Long> recruiterUserIdList = deliverList.stream()
                .map(Deliver::getRecruiterUserId)
                .filter(Objects::nonNull)
                .toList();
        List<Long> positionIdList = deliverList.stream()
                .map(Deliver::getPositionId)
                .filter(Objects::nonNull)
                .toList();
        List<Position> positions = recruiterCrossService.getPositionByIds(positionIdList);
        List<User> users = userCommonService.getUsersByUserIds(recruiterUserIdList);
        List<Recruiter> recruiters = recruiterCrossService.getRecruiterByUserIds(recruiterUserIdList);
        //构建map
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, elem -> elem));
        Map<Long, Recruiter> recruiterMap = recruiters.stream()
                .collect(Collectors.toMap(Recruiter::getUserId, elem -> elem));
        Map<Long, Position> positionMap = positions.stream()
                .collect(Collectors.toMap(Position::getPositionId, elem -> elem));
        for (Deliver deliver : deliverList) {
            SeekerCandidateResp resp = new SeekerCandidateResp();
            User user = userMap.get(deliver.getRecruiterUserId());
            Recruiter recruiter = recruiterMap.get(deliver.getRecruiterUserId());
            Position position = positionMap.get(deliver.getPositionId());
            BeanUtils.copyProperties(user, resp);
            BeanUtils.copyProperties(position, resp);
            BeanUtils.copyProperties(deliver, resp);
            resp.setRole(recruiter.getRole());
            respList.add(resp);
        }
        return respList;
    }
}
